Ext.namespace("Dudley");
Ext.namespace("Dudley.lims");

Dudley.lims.YOStrain = function() {

    var myYOData = [];
    var yoForm = {};
    var yoPanel = {};
    var yoHash = null;
    var yoCount = null;
    var yoMaxNum = null;
    var yoBox = 0;
    var yoPosition = null;
    var yoStore = null;
    var pagingBar = null;
    var spotlightMenu = sptlght.utils.SpotlightUtils.getSpotlightMenu("yospotlightmenuid");
    
    function initYOStore(callback) {
        Ext.Ajax.request({
            url: getSolrSearchUrl("yoFields:YO", 250, yoFields),
            method: "GET",
            success: function(response) {
                var searchResultObj = Ext.util.JSON.decode(response.responseText);
                console.log("Result count:" + searchResultObj.response.numFound);
                loadYOSearchResult(0, searchResultObj.response, callback);
            },
            failure: function() {
                Ext.Msg.alert("error", "Failed Initial YO Search, please contact Jake");
            }
        });
    }

    function loadYOSearchResult(index, searchResultJSON, callback) {
		yoStore = loadSolrSearchResult("YO", getPagingColumns(), yoSolrTranslator, index, searchResultJSON);
		yoStore.load({params:{start:0, limit:10}}, callback());
    }

    function goSearch(index, yoSearchInput, yoSearchOption) {
        if (yoSearchOption == null || yoSearchOption == 'All' || yoSearchOption == '') {
            yoSearchOption = "yoFields";            
        }
		if (yoSearchInput == '') {
                yoSearchInput = 'YO';
        }
        var searchUrl = getSolrSearchUrl(getLuceneTerm("yoFields", yoSearchInput), 2000, yoFields);
        var searchWin = getSearchLoadingWindow("yo-");
        searchWin.on("show", function () {
            var sb = Ext.getCmp("yo-search-statusbar");
            sb.showBusy();
        });
        searchWin.show();
        Ext.Ajax.request({
            url: searchUrl,
            method: "GET",
            success: function(response) {
                var searchResultObj = Ext.util.JSON.decode(response.responseText);
                myYOData = [];
                loadYOSearchResult(index, searchResultObj.response, function() {
                    Ext.getDom("sample-search-result-list").innerHTML = "";
                    Ext.getDom("yo-form").innerHTML = "";
                    searchWin.close();
                    renderYOSearchResult();
                });
            },
            failure: function() {
                console.log("Search Results failed for url:" + searchUrl);
                eventManager.fireStatusMessageEvent({ text: "Search Results failed for url:" + searchUrl, level: "error" });
            }
        });
    }

    function loadYOPanel() {
        var yosOptionsStore = new Ext.data.SimpleStore({
            fields: ['key', 'value'],
            data : getSampleSearchOptionsArray()
        });
        
        var yosCombo = new Ext.form.ComboBox({
            store: yosOptionsStore,
            name: 'yosCombo',
            id: 'yosComboId',
            fieldLabel: 'On Fields',
            displayField:'value',
            valueField:'key',
            typeAhead: true,
            mode: 'local',
            emptyText:'All',
            triggerAction: 'all',
            forceSelection:true,
            selectOnFocus:true
        });
        var dp = new Ext.DatePicker({
            format:"m/d/Y"
        });
        dp.on("select", function (t, d) {
            var myDateFormatted = d.format("m/d/Y");
            Ext.getCmp("yoSearchInputId").setValue(myDateFormatted);
            dateWin.hide();
        });
        var dateWin = new Ext.Window({
            title: 'DateFrozen Picker',
            width: 220,
            height: 250,
            modal: true,
            closeAction: 'hide',
            bodyStyle: 'padding:10px;',
            items:  dp
        });
        yosCombo.on("select", function (c, r, i) {
            if (i == 9) {
                dateWin.show();
            }
        });
        //var advancedSearchLink = '<A HREF="javascript:Dudley.lims.samplemgr.renderAdvancedSearch(\'' + "YO" + '\')">' + 'Advanced' + '</A>';
        var yoSearchForm = getSearchForm("yoSearchButtonId", "yoSearchInputId", null);
        Ext.getCmp("yoSearchButtonId").addListener("click", function(){
			goSearch(0, Ext.getCmp("yoSearchInputId").getValue(), "yoFields");		
		});		
        var tbarButtons = [
            {
                id: 'showYOSearchResultsId',
                name: 'showYOSearchResults',
                disabled: true,
                text: 'Search Results',
                icon: "images/back-green.png",
                cls:'x-btn-text-icon',
                tooltip: 'Displays previous searched results',
                listeners: {click:
                        function() {
                            Ext.getDom("yo-form").innerHTML = "";
                            renderYOSearchResult();
                        }
                }
            },
            {
                id: 'searchAllYOId',
                name: 'searchAllYO',
                disabled: false,
                text: 'View All Records',
                icon: "images/search-blue.png",
                cls:'x-btn-text-icon',
                tooltip: 'Lists all the wild strains',
                listeners: {click:
                        function() {
                            Ext.getDom("yo-form").innerHTML = "";
                            goSearch(0, '*', 'All');
                        }
                }
            },
            {
                id: 'createNewYOId',
                name: 'createNewYO',
                text: 'Create YO',
                icon: "images/add-green.png",
                cls:'x-btn-text-icon',
                tooltip: 'Creates new wild strain',
                listeners: {click:
                        function() {
                            var isolationConstructionButton = Ext.getCmp("isolationConstructionYOId");
                            if (isolationConstructionButton != null || isolationConstructionButton != undefined) {
                                isolationConstructionButton.disable();
                            }
                            Dudley.lims.YOStrain.loadNewYO();
                        }
                }
            }

        ];
        yoPanel = new Ext.Panel({
            id: "yoPanelId",
            autoHeight: true,
            border: true,
            renderTo: "yad-panel",
            title: "Natural Variant",
            header: false,
            tbar: tbarButtons,
            items: yoSearchForm
        });

        yoPanel.on("activate", function () {
            Ext.getDom("yad-panel").innerHTML = "";
            Ext.getDom("yad-form").innerHTML = "";
            Ext.getDom("yo-form").innerHTML = "";
            Ext.getDom("sample-search-result-list").innerHTML = "";
            renderYOSearchResult();
        });
    }

    function postYOStrain(createNew) {
        var yoPostJson = new Object();
        var strainName = Ext.getCmp("strainNameId").getValue();
        yoPostJson["yoKey"] = strainName;
        yoPostJson["yoAlias"] = Ext.getCmp("aliasId").getValue();
        yoPostJson["yoMatingType"] = Ext.getCmp("yoMatingTypeId").getValue();
        yoPostJson["yoMatingTypeMethod"] = Ext.getCmp("matingTypeDeterminationComboId").getValue();
        yoPostJson["yoPloidy"] = Ext.getCmp("ploidyComboId").getValue();
        yoPostJson["yoPloidyMethod"] = Ext.getCmp("ploidyDeterminationComboId").getValue();
        yoPostJson["yoStatus"] = Ext.getCmp("yoStatusId").getValue();
        yoPostJson["yoIsSC"] = Ext.getCmp("yoIsSCId").getValue();
        yoPostJson["yoIsSCMethod"] = Ext.getCmp("ceresiaeDeterminationComboId").getValue();
        yoPostJson["yoPloidyNotes"] = Ext.getCmp("ploidyNotesId").getValue();
        yoPostJson["yoGenotype"] = Ext.getCmp("genotypeId").getValue();
        yoPostJson["yoContributor"] = Ext.getCmp("contributorId").getValue();
        yoPostJson["yoSavedBy"] = Ext.getCmp("savedById").getValue();
        yoPostJson["yoParent"] = Ext.getCmp("strainParentsId").getValue();
        yoPostJson["yoProgenitor"] = Ext.getCmp("strainProgenitorId").getValue();
        yoPostJson["yoSiblings"] = Ext.getCmp("strainSiblingsId").getValue();
        yoPostJson["yoBoxNumber"] = Ext.getCmp("boxNumberId").getValue();
        yoPostJson["yoIsbNumber"] = Ext.getCmp("isbBoxNumberId").getValue();
        yoPostJson["yoPosition"] = Ext.getCmp("positionId").getValue();
        yoPostJson["yoDateFrozen"] = Ext.getCmp("dateFrozenId").getRawValue();
        yoPostJson["yoMTA"] = Ext.getCmp("mtaYOId").getValue();
        yoPostJson["yoComments"] = Ext.getCmp("commentsYOId").getValue();
        //QC
        yoPostJson["yoQCStatus"] = Ext.getCmp("qcFailureComboId").getValue();
        yoPostJson["yoQCReason"] = Ext.getCmp("qcFailureReasonComboId").getValue();
        yoPostJson["yoQCNotes"] = Ext.getCmp("qcNotesId").getValue();
        //Geography/Env
        yoPostJson["yoContinent"] = Ext.getCmp("continentComboId").getValue();
        yoPostJson["yoCountry"] = Ext.getCmp("countryComboId").getValue();
        yoPostJson["yoLocale"] = Ext.getCmp("localeId").getValue();
        yoPostJson["yoGeoNotes"] = Ext.getCmp("geographyNotesId").getValue();
        yoPostJson["yoEnvSource"] = Ext.getCmp("environmentSourceComboId").getValue();
        yoPostJson["yoGeoDate"] = Ext.getCmp("geographyDateId").getValue();
        yoPostJson["yoEnvNotes"] = Ext.getCmp("environmentNotesId").getValue();
        var boxNumber = parseInt(Ext.getCmp("boxNumberId").getValue());
        var position = Ext.getCmp("positionId").getValue();
        var strainOp = "create";
        var yoCallback = function() {
            var yoBoxVal = parseInt(yoBox);
            if (boxNumber >= yoBox) {
                yoBoxVal = boxNumber;
            }
            var yoPositionVal = yoPosition;
            if (isNewPosition(yoPosition, position)) {
                yoPositionVal = position;
            }
            limsadmin_obj["limsadminYoCount"] = yoCount; 
            limsadmin_obj['limsadminYoMaxNum'] = yoMaxNum;
            limsadmin_obj['limsadminYoBoxNum'] = yoBoxVal;
            limsadmin_obj['limsadminYoPosition'] = yoPositionVal;            
            postSolrUpdates(limsadmin_obj, function(){
                Ext.Msg.alert('Info', "NV Strain " + strainName + ' Added Successfully');
                Ext.getDom("yo-form").innerHTML = "";
                goSearch(0, strainName, "yoKey");
            });
        };
        if (!createNew) {
            strainOp = "annotations";
            yoCallback = function() {
                Ext.Msg.alert('Info', strainName + ' Updated Successfully');
                var searchResultsButton = Ext.getCmp("showYOSearchResultsId");
                searchResultsButton.disable();
            };
        }
        postSolrUpdates(yoPostJson, yoCallback);
    }
    
    function loadCreateWildStrain(yoHash, callback) {
        metaPanel.collapse();
        var createNew = true;
        var nvtaskDisabled = true;
        var portalPanel = new Ext.Panel({});
        var buttons = [
            {
                id: 'createButton',
                name: 'createButton',
                text: 'Create',
                listeners: {click:
                        function() {
                            if (validateCreateWildStrain('YO')) {
                                postYOStrain(createNew);
                            }
                        }
                }
            }
        ];
        if (yoHash != null && yoHash["clone"] == undefined) {
            if (yoHash.genotype != undefined && yoHash.genotype == 'Record Deleted') {
                buttons = [];
            } else {
                buttons = [
                    {
                        id: 'updateYOButtonId',
                        name: 'updateYOButton',
                        text: 'Update',
                        listeners: {click:
                                function() {
                                    if (validateCreateWildStrain('YO')) {
                                        postYOStrain(!createNew);
                                    }
                                }
                        }
                    },
                    {
                        id: 'deleteYOButtonId',
                        name: 'deleteYOButton',
                        text: 'Delete',
                        listeners: {click:
                                function() {
                                    var deleteUrl = "/addama-rest/dudley-sample/path/datasource/YO/" + yoHash.name + "/annotations/?JSON={deletedStrain:true}";
                                    Ext.Msg.confirm('Message', "Are you sure you want to delete " + yoHash.name + "?", function(btn) {
                                        if (btn == 'yes') {
                                            Ext.Ajax.request({
                                                url: deleteUrl,
                                                method: "POST",
                                                success: function() {
                                                    Ext.Msg.alert(yoHash.name + " deleted, YO Strains Reloading...");
                                                    goSearch(0, '*', 'All');
                                                },
                                                failure: function() {
                                                    eventManager.fireStatusMessageEvent({ text: "Delete Failed for " + yoHash.name, level: "error" });
                                                }
                                            });
                                        }
                                    });
                                }
                        }
                    }
                ];
            }
            if (yoHash.isSC == null || yoHash.isSC == "") {
                yoHash.isSC = "Unknown";
            }
            if (yoHash.comments == null) {
                yoHash.comments = "";
            }
            if (yoHash.mta == null) {
                yoHash.mta = "";
            }
            portalPanel = new Ext.Panel({
                id: "yoImagePanelId",
                autoHeight: true,
                title: "Strain Meta Data",
                autoWidth: true,
                header: true,
                html: "<a href='javascript:placeHolder()'><img src='images/search-blue.png' border='0'>Image View Portal</a>"
                        + "&nbsp;" + "<a href='javascript:placeHolder()'><img src='images/search-blue.png' border='0'>Sequence View Portal</a>"
                        + "&nbsp;" + "<a href='javascript:placeHolder()'><img src='images/search-blue.png' border='0'>Proteomics View Portal</a>"
                        + "&nbsp;" + "<a href='javascript:placeHolder()'><img src='images/search-blue.png' border='0'>RNA View Portal</a>"
            });
            nvtaskDisabled = false;
        } else {
	    if (yoHash == null)
            	yoHash = new Object();
            var yoMaxInt = parseInt(yoMaxNum);
            yoMaxInt = yoMaxInt + 1;
            var yoCountInt = parseInt(yoCount);
            yoCountInt = yoCountInt + 1;
            yoCount = yoCountInt + "";
            //yoHash.name = 'YO' + yoMaxInt;
            //yoHash.strainName = 'YO' + yoMaxInt;
            yoHash.boxNumber = yoBox;
            yoHash.position = getNextPosition(yoPosition);
            if (yoPosition == "I9") {
                yoHash.boxNumber = parseInt(yoBox) + 1;
            }
            yoMaxNum = yoMaxInt + "";
	    var dash = "_";
	    if (yoHash.clone != undefined){
                yoHash.comments = yoHash.comments + " cloned from " + yoHash.name;
                //reset key fields
		resetKeyFields(yoHash);
		//if (yoHash.siblings == null || yoHash.siblings.length < 1){
		//	dash = "";
		//}
	        //yoHash.siblings = yoHash.siblings + dash + yoHash.name;
            }
	    yoHash.name = 'YO' + yoMaxInt;
            yoHash.strainName = 'YO' + yoMaxInt;
            initStrainJson(yoHash);
        }
        Ext.QuickTips.init();  // enable tooltips
        var mytbar = [
            {
                id: 'familtreeYOId',
                disabled: nvtaskDisabled,
                text: 'Family Tree',
                icon: "images/familytree.png",
                cls:'x-btn-text-icon',
                tooltip: 'Displays family tree chart',
                listeners: {click:
                        function() {
                            loadFamilyTree();
                        }
                }
            },
            {
                id: 'isolationConstructionYOId',
                name: 'isolationConstructionYO',
                disabled: nvtaskDisabled,
                text: 'QC_IsoConstruction',
                icon: "images/star.png",
                cls:'x-btn-text-icon',
                tooltip: 'Renders input form for Isolation Construction workflow',
                listeners: {click:
                        function() {
                            popupQCForm(yoHash);
                        }
                }
            },
            {
                id: 'omicsYOId',
                name: 'omicsYO',
                disabled: nvtaskDisabled,
                text: 'Omics Data',
                icon: "images/info.png",
                cls:'x-btn-text-icon',
                tooltip: 'Displays associated omics data (Sequencing, Crosses, Imaging, Proteomics, Metabolites) associated with strain',
                listeners: {
                    click: function() {
                        Dudley.lims.YOStrain.viewOmicsTable();
                    }
                }
            }, 
            {
                id: 'detailSpotlightYOId',
                disabled: nvtaskDisabled,
                text: 'Spotlight',
                icon: "images/add-green.png",
                cls:'x-btn-text-icon',
                tooltip: 'Add to spotlight',
                listeners: {
                    click: function() {
                        var selectedArray = [yoHash.name, yoHash.name, yoHash.alias];
                        sptlght.utils.SpotlightUtils.setSelectedRecord(selectedArray);
                        sptlght.utils.SpotlightUtils.setSource("yo");
                        sptlght.utils.SpotlightUtils.handleAddToSpotlight();
                    }
                }
	    },
               {
                    id: 'cloneYOId',
                    disabled: nvtaskDisabled,
                    text: 'Clone',
                    icon: "images/hourglass.png",
                    cls:'x-btn-text-icon',
                    tooltip: 'Clone',
                    listeners: {
                        click: function() {
                            var cloneWin = new Ext.Window({
                title: 'YOClone - Select fields',
                width: 600,
                height: 450,
                autoScroll: true,
                modal: true,
                bodyStyle: 'padding:2px;',
                items: [customcloneboxes],
                buttons: [
                    {
                        text: 'SelectAll',
                        handler: function() {
                            Ext.getCmp("clonealiascb").setValue(true);
                            Ext.getCmp("clonematingtypecb").setValue(true);
			    Ext.getCmp("clonematingtypecb").setValue(true);
                            Ext.getCmp("cloneissccb").setValue(true);
                            Ext.getCmp("cloneisscmethodcb").setValue(true);
                            Ext.getCmp("cloneploidycb").setValue(true);
                            Ext.getCmp("cloneploidymethodcb").setValue(true);
                            Ext.getCmp("cloneploidynotescb").setValue(true);
                            Ext.getCmp("clonegenotypecb").setValue(true);
                            Ext.getCmp("cloneparentcb").setValue(true);
                            Ext.getCmp("cloneprogenitorcb").setValue(true);
                            Ext.getCmp("clonesiblingscb").setValue(true);
                            Ext.getCmp("clonecontinentcb").setValue(true);
                            Ext.getCmp("clonecountrycb").setValue(true);
                            Ext.getCmp("clonelocalecb").setValue(true);
                            Ext.getCmp("clonegeodatecb").setValue(true);
                            Ext.getCmp("cloneenvsourcecb").setValue(true);
                            Ext.getCmp("clonegeonotescb").setValue(true);
                            Ext.getCmp("cloneenvnotescb").setValue(true);
                            Ext.getCmp("cloneboxnumbercb").setValue(true);
                            Ext.getCmp("cloneisbnumbercb").setValue(true);
                            Ext.getCmp("clonepositioncb").setValue(true);
                            Ext.getCmp("clonedatefrozencb").setValue(true);
                            Ext.getCmp("clonecontributorcb").setValue(true);
                            Ext.getCmp("clonecommentscb").setValue(true);
                            Ext.getCmp("clonesavedbycb").setValue(true);
                            Ext.getCmp("clonemtacb").setValue(true);
                            Ext.getCmp("clonestatuscb").setValue(true);
                            Ext.getCmp("cloneqcstatuscb").setValue(true);
                            Ext.getCmp("cloneqcreasoncb").setValue(true);
                            Ext.getCmp("cloneqcnotescb").setValue(true);
                        }
                    },
				 {
                        text: 'Reset',
                        handler: function() {
                            Ext.getCmp("clonealiascb").setValue(false);
                            Ext.getCmp("clonematingtypecb").setValue(false);
			    Ext.getCmp("clonemtmethodcb").setValue(false);
                            Ext.getCmp("cloneissccb").setValue(false);
                            Ext.getCmp("cloneisscmethodcb").setValue(false);
                            Ext.getCmp("cloneploidycb").setValue(false);
                            Ext.getCmp("cloneploidymethodcb").setValue(false);
                            Ext.getCmp("cloneploidynotescb").setValue(false);
                            Ext.getCmp("clonegenotypecb").setValue(false);
                            Ext.getCmp("cloneparentcb").setValue(false);
                            Ext.getCmp("cloneprogenitorcb").setValue(false);
                            Ext.getCmp("clonesiblingscb").setValue(false);
                            Ext.getCmp("clonecontinentcb").setValue(true);
                            Ext.getCmp("clonecountrycb").setValue(true);
                            Ext.getCmp("clonelocalecb").setValue(true);
                            Ext.getCmp("clonegeodatecb").setValue(true);
                            Ext.getCmp("cloneenvsourcecb").setValue(true);
                            Ext.getCmp("clonegeonotescb").setValue(true);
                            Ext.getCmp("cloneenvnotescb").setValue(true);
                            Ext.getCmp("cloneboxnumbercb").setValue(true);
                            Ext.getCmp("cloneisbnumbercb").setValue(true);
                            Ext.getCmp("clonepositioncb").setValue(true);
                            Ext.getCmp("clonedatefrozencb").setValue(true);
                            Ext.getCmp("clonecontributorcb").setValue(true);
                            Ext.getCmp("clonecommentscb").setValue(true);
                            Ext.getCmp("clonesavedbycb").setValue(true);
                            Ext.getCmp("clonestatuscb").setValue(false);
                            Ext.getCmp("clonemtacb").setValue(true);
                            Ext.getCmp("cloneqcstatuscb").setValue(true);
                            Ext.getCmp("cloneqcreasoncb").setValue(true);
                            Ext.getCmp("cloneqcnotescb").setValue(true);
                        }
                    },
                    {
                        text: 'Go',
                        handler: function() {
                            	yoHash["clone"] = 1;
                                nvtaskDisabled = true;
                        	getSolrLimsAdmin(setYoAdmin);
                        	cloneWin.hide();
			}
                    }
                ],
                layout: 'fit'
            	});
            	cloneWin.show();
			 }
                    }
            }
        ];
        yoForm = new Ext.form.FormPanel({
            id: 'yoForm',
            method: 'POST',
            autoHeight: true,
            autoScroll: true,
            title: "Natural Variant",
            border: true,
            buttonAlign: 'left',
            tbar: mytbar,
            buttons: buttons,
            items: [
                new Ext.form.FieldSet({
                    autoHeight: true,
                    border: false,
                    items: [
                        new Ext.form.TextField({
                            id: "strainNameId",
                            fieldLabel: "Key",
                            name: "strainName",
                            value: yoHash.name,
                            width: 500,
                            readOnly: true,
                            allowBlank: false,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Required: A YO key that uniquely identifies this version of this strain (for example duplicate copies of the same strain are' +
                                              ' assigned different YO numbers), the field is system generated and can not be changed.'
                                    });

                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "aliasId",
                            fieldLabel: "Alias",
                            name: "strainAlias",
                            value: yoHash.alias,
                            width: 500,
                            allowBlank: false,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Required: Alias is a name by which the strain and its derivatives is known to the outside world (e.g. RM11-1a), this identifier is ' +
                                              'not necessarily unique (for example we may have several copies of RM11-1a).'
                                    });
                                }
                            }
                        }),
                        new Ext.form.ComboBox({
                            store: yoStatusStore,
                            id: 'yoStatusId',
                            fieldLabel: 'Processing State ',
                            displayField:'value',
                            valueField:'key',
                            typeAhead: true,
                            mode: 'local',
                            triggerAction: 'all',
                            value:yoHash.status,
                            forceSelection:true,
                            selectOnFocus:true,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Strain processing(modification) state; determined by Dudley Lab QC/Isolation_Construction protocol'
                                    });
                                }
                            }
                        }),
                        {
                            xtype: 'fieldset',
                            title: 'QC Status/Data',
                            width: 605,
                            collapsed: true,
                            collapsible: true,
                            items: [
                                {
                                    layout: 'hbox',
                                    width: 500,
                                    fieldLabel: 'Status',
                                    msgTarget: 'under',
                                    items: [
                                        {
                                            xtype: 'displayfield',
                                            value: '&nbsp;Failed QC?:&nbsp;'
                                        },
                                        {
                                            xtype: 'combo',
                                            id: 'qcFailureComboId',
                                            value: yoHash.qcFailure,
                                            width: 150,
                                            store: yesNoStore,
                                            displayField: 'key',
                                            valueField: 'value',
                                            selectOnFocus: true,
                                            mode: 'local',
                                            typeAhead: true,
                                            editable: false,
                                            triggerAction: 'all',
                                            margins: '0 5 0 0'
                                        },
                                        {
                                            xtype: 'displayfield',
                                            value: '&nbsp;Reason:&nbsp;'
                                        },
                                        {
                                            xtype: 'combo',
                                            id: 'qcFailureReasonComboId',
                                            value: yoHash.qcFailureReason,
                                            width: 150,
                                            store: qcFailureReasonStore,
                                            displayField: 'key',
                                            valueField: 'value',
                                            selectOnFocus: true,
                                            mode: 'local',
                                            typeAhead: true,
                                            editable: false,
                                            triggerAction: 'all',
                                            margins: '0 5 0 0'
                                        }
                                    ]
                                },
                                new Ext.form.TextField({
                                    id: "qcNotesId",
                                    fieldLabel: "QC Notes",
                                    value: yoHash.qcNotes,
                                    width: 500,
                                    allowBlank: true,
                                    listeners: {
                                        render: function(c) {
                                            Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'QC Notes, such as more details about reason for failure'
                                            });
                                        },
                                        change: function(t, n, o) {
                                            var washed = replacedIllegalEntries(n);
                                            t.setValue(washed);
                                        }
                                    }
                                })
                            ]
                        },
                        {
                            layout: 'hbox',
                            width: 500,
                            fieldLabel: 'S. cerevisiae?',
                            msgTarget: 'under',
                            items: [
                                new Ext.form.ComboBox({
                                    store: yesNoStore,
                                    name: 'yoIsSC',
                                    id: 'yoIsSCId',
                                    fieldLabel: 'S. cerevisiae?',
                                    displayField:'value',
                                    valueField:'key',
                                    typeAhead: true,
                                    mode: 'local',
                                    triggerAction: 'all',
                                    value:yoHash.isSC,
                                    forceSelection:true,
                                    selectOnFocus:true,
                                    listeners: {
                                        render: function(c) {
                                            Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'Indicates Whether Strain is S. cerevisiae'
                                            });

                                        }
                                    }
                                }),
                                {
                                    xtype: 'displayfield',
                                    value: '&nbsp;Determination method:&nbsp;'
                                },
                                {
                                    xtype: 'combo',
                                    id: 'ceresiaeDeterminationComboId',
                                    value: yoHash.ceresiaeDetermination,
                                    width: 180,
                                    store: ceresiaeDeterminationStore,
                                    displayField: 'key',
                                    valueField: 'value',
                                    selectOnFocus: true,
                                    mode: 'local',
                                    typeAhead: true,
                                    editable: false,
                                    triggerAction: 'all',
                                    margins: '0 5 0 0',
                                    listeners: {
                                        render: function(c) {
                                            Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'S. cerevisiae determination method'
                                            });
                                        }
                                    }
                                }
                            ]
                        },
                        {
                            layout: 'hbox',
                            width: 500,
                            fieldLabel: 'Mating type',
                            msgTarget: 'under',
                            items: [
                                {
                                    xtype: 'displayfield',
                                    value: '&nbsp;Type:&nbsp;'
                                },
                                new Ext.form.ComboBox({
                                    store: matingTypeStore,
                                    name: 'yoMatingType',
                                    id: 'yoMatingTypeId',
                                    fieldLabel: 'Mating Type',
                                    displayField:'value',
                                    valueField:'key',
                                    width: 150,
                                    typeAhead: true,
                                    mode: 'local',
                                    triggerAction: 'all',
                                    value:yoHash.matingType,
                                    forceSelection:true,
                                    selectOnFocus:true,
                                    listeners: {
                                        render: function(c) {
                                            Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'Mating type is required'
                                            });
                                        }
                                    }
                                }),
                                {
                                    xtype: 'displayfield',
                                    value: '&nbsp;Determination method:&nbsp;'
                                },
                                {
                                    xtype: 'combo',
                                    id: 'matingTypeDeterminationComboId',
                                    value: yoHash.matingTypeDetermination,
                                    width: 100,
                                    store: matingDeterminationStore,
                                    displayField: 'key',
                                    valueField: 'value',
                                    selectOnFocus: true,
                                    mode: 'local',
                                    typeAhead: true,
                                    editable: false,
                                    triggerAction: 'all',
                                    margins: '0 5 0 0',
                                    listeners: {
                                        render: function(c) {
                                            Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'Mating type determination method'
                                            });
                                        }
                                    }
                                }
                            ]
                        },
                        {
                            layout: 'hbox',
                            width: 500,
                            fieldLabel: 'Ploidy',
                            msgTarget: 'under',
                            items: [
                                {
                                    xtype: 'displayfield',
                                    value: '&nbsp;Type:&nbsp;'
                                },
                                {
                                    xtype: 'combo',
                                    id: 'ploidyComboId',
                                    width: 150,
                                    store: ploidyStore,
                                    displayField: 'key',
                                    valueField: 'value',
                                    selectOnFocus: true,
                                    mode: 'local',
                                    typeAhead: true,
                                    editable: false,
                                    triggerAction: 'all',
                                    value: yoHash.ploidy,
                                    listeners: {
                                        render: function(c) {
                                            Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'Strain ploidy'
                                            });
                                        }
                                    }
                                },
                                {
                                    xtype: 'displayfield',
                                    value: '&nbsp;Determination method:&nbsp;'
                                },
                                {
                                    xtype: 'combo',
                                    id: 'ploidyDeterminationComboId',
                                    value: yoHash.ploidyDetermination,
                                    width: 100,
                                    store: ploidyDeterminationStore,
                                    displayField: 'key',
                                    valueField: 'value',
                                    selectOnFocus: true,
                                    mode: 'local',
                                    typeAhead: true,
                                    editable: false,
                                    triggerAction: 'all',
                                    margins: '0 5 0 0',
                                    listeners: {
                                        render: function(c) {
                                            Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'Ploidy Determination method'
                                            });
                                        }
                                    }
                                }
                            ]
                        },
                        new Ext.form.TextField({
                            id: "ploidyNotesId",
                            fieldLabel: "Mating Type/Ploidy Notes",
                            name: "ploidyNotes",
                            value: yoHash.ploidyNotes,
                            width: 500,
                            allowBlank: true
                        }),
                        new Ext.form.TextField({
                            id: "genotypeId",
                            fieldLabel: "Genotype",
                            name: "strainGenotype",
                            value: yoHash.genotype,
                            width: 500,
                            allowBlank: true
                        }),
                        {
                            xtype: 'fieldset',
                            title: 'Geography and Environment Source/Info',
                            width: 605,
                            collapsed: true,
                            collapsible: true,
                            items: [
                                {
                                    layout: 'hbox',
                                    width: 500,
                                    fieldLabel: 'Geography',
                                    msgTarget: 'under',
                                    items: [
                                        {
                                            xtype: 'displayfield',
                                            value: 'Continent&nbsp;'
                                        },
                                        {
                                            xtype: 'combo',
                                            id: 'continentComboId',
                                            emptyText: 'Unknown ',
                                            width: 125,
                                            store: continentStore,
                                            displayField: 'key',
                                            valueField: 'value',
                                            selectOnFocus: true,
                                            mode: 'local',
                                            typeAhead: true,
                                            editable: false,
                                            triggerAction: 'all',
                                            value: yoHash.continent,
                                            margins: '0 5 0 0'
                                        },
                                        {
                                            xtype: 'displayfield',
                                            value: 'Country&nbsp;'
                                        },
                                        {
                                            xtype: 'combo',
                                            id: 'countryComboId',
                                            emptyText: 'Unknown ',
                                            value: yoHash.country,
                                            width: 125,
                                            store: countryStore,
                                            displayField: 'key',
                                            valueField: 'value',
                                            selectOnFocus: true,
                                            mode: 'local',
                                            typeAhead: true,
                                            editable: false,
                                            triggerAction: 'all',
                                            margins: '0 5 0 0'
                                        }
                                    ]
                                },
                                {
                                    layout: 'hbox',
                                    width: 500,
                                    fieldLabel: "Additional",
                                    msgTarget: 'under',
                                    items: [
                                        {
                                            xtype: 'displayfield',
                                            value: 'Locale&nbsp;'
                                        },
                                        {
                                            xtype: 'textfield',
                                            id: 'localeId',
                                            value: yoHash.locale,
                                            width: 200,
                                            flex: 1,
                                            allowBlank: true,
                                            margins: '0 5 0 0',
                                            listeners: {
                                                render: function(c) {
                                                    Ext.QuickTips.register({
                                                        target: c,
                                                        title: '',
                                                        text: 'Geography locale description'
                                                    });
                                                }
                                            }
                                        },
                                        {
                                            xtype: 'displayfield',
                                            value: 'Month/Year&nbsp;'
                                        },
                                        {
                                            xtype: 'textfield',
                                            id: 'geographyDateId',
                                            value: yoHash.geographyDate,
                                            width: 200,
                                            flex: 1,
                                            allowBlank: true,
                                            margins: '0 5 0 0',
                                            listeners: {
                                                render: function(c) {
                                                    Ext.QuickTips.register({
                                                        target: c,
                                                        title: '',
                                                        text: 'Geography date, month/year'
                                                    });
                                                }
                                            }
                                        }
                                    ]
                                },

                                new Ext.form.TextField({
                                    id: "geographyNotesId",
                                    fieldLabel: "Geography Notes",
                                    value: yoHash.strainSource,
                                    width: 500,
                                    allowBlank: true,
                                    listeners: {
                                        render: function(c) {
                                            Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'Geography Notes: #, &, %, @, and single/double quotes are not allowed'
                                            });
                                        },
                                        change: function(t, n, o) {
                                            var washed = replacedIllegalEntries(n);
                                            t.setValue(washed);
                                        }
                                    }
                                }),
                                {
                                    layout: 'hbox',
                                    width: 500,
                                    fieldLabel: 'Environment Source',
                                    msgTarget: 'under',
                                    items: [
                                        {
                                            xtype: 'combo',
                                            id: 'environmentSourceComboId',
                                            width: 150,
                                            store: environmentSourceStore,
                                            displayField: 'key',
                                            valueField: 'value',
                                            selectOnFocus: true,
                                            mode: 'local',
                                            typeAhead: true,
                                            editable: false,
                                            triggerAction: 'all',
                                            value: yoHash.environmentSource
                                        }

                                    ]
                                },
                                new Ext.form.TextField({
                                    id: "environmentNotesId",
                                    fieldLabel: "Environment Notes",
                                    value: yoHash.environmentNotes,
                                    width: 500,
                                    allowBlank: true,
                                    listeners: {
                                        render: function(c) {
                                            Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'Environment notes'
                                            });
                                        },
                                        change: function(t, n, o) {
                                            t.setValue(replacedIllegalEntries(n));
                                        }
                                    }
                                })
                            ]
                        },
                        new Ext.form.TextField({
                            id: "contributorId",
                            fieldLabel: "Contributor",
                            name: "contributor",
                            value: yoHash.contributor,
                            width: 500,
                            allowBlank: true,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Contributing source, who sent us this strain'
                                    });
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "savedById",
                            fieldLabel: "Saved by",
                            value: yoHash.savedBy,
                            width: 500,
                            allowBlank: true,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Person saving this strain into LIMS'
                                    });
                                }
                            }
                        }),
                        {
                            layout: 'hbox',
                            width: 500,
                            fieldLabel: 'Family',
                            msgTarget: 'under',
                            items: [
                                {
                                    xtype: 'displayfield',
                                    value: '&nbsp;Parents:&nbsp;'
                                },
                                new Ext.form.TextField({
                                    id: "strainParentsId",
                                    labelSeparator: '',
                                    value: yoHash.strainParents,
                                    width: 100,
                                    allowBlank: true,
                                    listeners: {
                                        render: function(c) {
                                            Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'Immediate parent of strain'
                                            });
                                        }
                                    }
                                }),
                                {
                                    xtype: 'displayfield',
                                    value: '&nbsp;Progenitor:&nbsp;'
                                },
                                new Ext.form.TextField({
                                    id: "strainProgenitorId",
                                    labelSeparator: '',
                                    value: yoHash.strainProgenitor,
                                    width: 100,
                                    allowBlank: true,
                                    listeners: {
                                        render: function(c) {
                                            Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'The oldest/original parent of strain'
                                            });
                                        }
                                    }
                                }),
                                {
                                    xtype: 'displayfield',
                                    value: '&nbsp;Sister spores:&nbsp;'
                                },
                                new Ext.form.TextField({
                                    id: "strainSiblingsId",
                                    labelSeparator: '',
                                    value: yoHash.siblings,
                                    width: 100,
                                    allowBlank: true,
                                    listeners: {
                                        render: function(c) {
                                            Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'Spores sharing the same immediate parent'
                                            });
                                        }
                                    }
                                })
                            ]
                        },
                        {
                            layout: 'hbox',
                            width: 500,
                            fieldLabel: 'Physical Location',
                            msgTarget: 'under',
                            items: [
                                {
                                    xtype: 'displayfield',
                                    value: '&nbsp;Box number:&nbsp;'
                                },
                                new Ext.form.TextField({
                                    id: "boxNumberId",
                                    name: "boxNumber",
                                    value: yoHash.boxNumber,
                                    width: 75,
                                    allowBlank: false,
                                    listeners: {
                                        render: function(c) {
                                            Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'Strain box number'
                                            });
                                        }
                                    }
                                }),
                                {
                                    xtype: 'displayfield',
                                    value: '&nbsp;ISB number:&nbsp;'
                                },
                                new Ext.form.TextField({
                                    id: "isbBoxNumberId",
                                    name: "isbBoxNumber",
                                    value: yoHash.isbBoxNumber,
                                    width: 75,
                                    allowBlank: false,
                                    listeners: {
                                        render: function(c) {
                                            Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'ISB Assigned Strain box number'
                                            });
                                        }
                                    }
                                }),
                                {
                                    xtype: 'displayfield',
                                    value: '&nbsp;Position:&nbsp;'
                                },
                                new Ext.form.TextField({
                                    id: "positionId",
                                    fieldLabel: "Position",
                                    name: "position",
                                    value: yoHash.position,
                                    width: 75,
                                    allowBlank: true,
                                    listeners: {
                                        render: function(c) {
                                            Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'Strain physical position'
                                            });
                                        }
                                    }
                                }),
                            ]
                        },
                        new Ext.form.DateField({
                            id: "dateFrozenId",
                            fieldLabel: "Date Frozen",
                            name: "dateFrozen",
                            value: yoHash.dateFrozen,
                            size: 20,
                            allowBlank: false,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Strain date frozened'
                                    });
                                }
                            }
                        }),
                        {
                            xtype:'htmleditor',
                            id:'mtaYOId',
                            value: yoHash.mta,
                            fieldLabel:'Legal Documents ' + '<br><i><font size=-2>link to Material Transfer Agreement or other legal documentation</font></i>',
                            height:100,
                            anchor:'98%',
                            listeners: {
                                activate: function(e) {
                                    if (yoHash.mta == undefined || yoHash.mta == "") {
                                        e.execCmd('delete');
                                    }
                                }
                            }
                        },
                        {
                            xtype:'htmleditor',
                            id:'commentsYOId',
                            value: yoHash.comments,
                            fieldLabel:'Comments ' + '<br><i><font size=-2>Relevant information about the strain not covered in other fields</font></i>',
                            height:100,
                            labelSeparator: '',
                            anchor:'98%',
                            listeners: {
                                activate: function(e) {
                                    if (yoHash.comments == undefined || yoHash.comments == "") {
                                        e.execCmd('delete');
                                    }
                                }/*,
                                 'initialize': function(f) {
                                 if (document.all) {
                                 f.iframe.attachEvent("onblur", function() {
                                 on_editor_blur("commentsYOId");
                                 });
                                 }
                                 else {
                                 f.iframe.contentDocument.addEventListener("blur", function() {
                                 on_editor_blur("commentsYOId");
                                 }, false);
                                 }
                                 }*/
                            }
                        }

                    ]
                })
            ]
        });
        callback();
    }

    function doSearch() {
        renderYOSearchResult();
    }

    // render the grid to the specified div in the page
    function renderYOSearchResult() {
        if (myYOData.length == 1) {
            renderStrainDetails(null);
            return;
        }
        var searchResultsButton = Ext.getCmp("showYOSearchResultsId");
        if (searchResultsButton != null || searchResultsButton != undefined) {
            searchResultsButton.disable();
        }
        var mytbar = [
            {
                id: 'yo2CSVId',
                text: 'Export2CSV',
                icon: "images/check-green.png",
                cls:'x-btn-text-icon',
                tooltip: 'Export search results to csv',
                listeners: {click:
                        function() {
                            Dudley.lims.YOStrain.toCSV();
                        }
                }
            }
        ];
        pagingBar = new Ext.PagingToolbar({
            pageSize: 10,
            store: yoStore,
            displayInfo: true,
            displayMsg: 'Displaying strains {0} - {1} of {2}',
            emptyMsg: "No strains to display"
        });
        var searchResultsGrid = new Ext.grid.GridPanel({
            id: "yoSearchResultsId",
            store: yoStore,
            columns: getStrainSearchColumnHeaders("YO"),
            stripeRows: true,
            autoExpandColumn: 'name',
            autoHeight: true,
            width: 800,
            title: 'Natural Variant Strain Collection',
            renderTo: "sample-search-result-list",
            tbar: mytbar,
            bbar: pagingBar
        });
        searchResultsGrid.on("celldblclick", function (g, ri, ci, e) {
            renderStrainDetails(g);
        });
        searchResultsGrid.on("rowcontextmenu", onMessageContextMenu);
    }

    function onMessageContextMenu(grid, rowIndex, e) {
        var activePage = Math.ceil((pagingBar.cursor + pagingBar.pageSize) / pagingBar.pageSize);
        var realIndex = (activePage - 1) * pagingBar.pageSize + rowIndex;
        sptlght.utils.SpotlightUtils.setSelectedRecord(yoStore.allData.items[realIndex].json);
        sptlght.utils.SpotlightUtils.setSource("yo");
        e.preventDefault();
        e.stopEvent();
        var coords = e.getXY();
        spotlightMenu.showAt([coords[0], coords[1]]);
    }

    function renderStrainDetails(g) {
        var searchResultsButton = Ext.getCmp("showYOSearchResultsId");
        searchResultsButton.enable();
        yoHash = new Object();
        if (g != null) {
            populateStrainJson(yoHash, g);
            yoHash.name = g.getSelectionModel().getSelected().data.name;
        }
        else {
            populateSingleStrainViaArray(yoHash, myYOData[0]);
        }
        loadCreateWildStrain(yoHash, function() {
            yoFormRender();
        });
    }

    function yoFormRender() {
        Dudley.lims.samplemgr.getHousingPanel().activate(yoPanel);
        Ext.getDom("sample-search-result-list").innerHTML = "";
        Ext.getDom("yo-form").innerHTML = "";
        yoForm.render("yo-form");
        //loadFamilyTree();
    }

    function loadFamilyTree() {
        drawVisualization(yoHash);
    }

    function loadSeqTable() {
        drawSeqSampleTable(yoHash);
    }

    function processYO2CSV(csvData) {
        var csvText = "yoKey";
        var statusck,aliasck,mtack,mtck,mtmethodck,isscck,isscmethodck,ploidyck,ploidymethodck,genotypeck,parentck,progenitorck,siblingsck,continentck,countryck,localeck,geodateck,envsourceck,geonotesck,envnotesck,boxnumberck,isbnumberck,positionck,datefrozenck,contributorck,savedbyck,commentsck = false;
        if (Ext.getCmp("statuscb").getValue())
            csvText = csvText + ",yoStatus",statusck = true;
        if (Ext.getCmp("aliascb").getValue())
            csvText = csvText + ",yoAlias",aliasck = true;
        if (Ext.getCmp("matingtypecb").getValue())
            csvText = csvText + ",yoMatingType",mtck = true;
        if (Ext.getCmp("mtmethodcb").getValue())
            csvText = csvText + ",yoMatingTypeMethod",mtmethodck = true;
        if (Ext.getCmp("issccb").getValue())
            csvText = csvText + ",yoIsSC",isscck = true;
        if (Ext.getCmp("isscmethodcb").getValue())
            csvText = csvText + ",yoIsSCMethod",isscmethodck = true;
        if (Ext.getCmp("ploidycb").getValue())
            csvText = csvText + ",yoPloidy",ploidyck = true;
        if (Ext.getCmp("ploidymethodcb").getValue())
            csvText = csvText + ",yoPloidyMethod",ploidymethodck = true;
        if (Ext.getCmp("ploidynotescb").getValue())
            csvText = csvText + ",yoPloidyNotes";
        if (Ext.getCmp("genotypecb").getValue())
            csvText = csvText + ",yoGenotype",genotypeck = true;
        if (Ext.getCmp("parentcb").getValue())
            csvText = csvText + ",yoParent",parentck = true;
        if (Ext.getCmp("progenitorcb").getValue())
            csvText = csvText + ",yoProgenitor",progenitorck = true;
        if (Ext.getCmp("siblingscb").getValue())
            csvText = csvText + ",yoSiblings",siblingsck = true;
        if (Ext.getCmp("continentcb").getValue())
            csvText = csvText + ",yoContinent",continentck = true;
        if (Ext.getCmp("countrycb").getValue())
            csvText = csvText + ",yoCountry",countryck = true;
        if (Ext.getCmp("localecb").getValue())
            csvText = csvText + ",yoLocale",localeck = true;
        if (Ext.getCmp("geodatecb").getValue())
            csvText = csvText + ",yoGeoDate",geodateck = true;
        if (Ext.getCmp("envsourcecb").getValue())
            csvText = csvText + ",yoEnvSource",envsourceck = true;
        if (Ext.getCmp("geonotescb").getValue())
            csvText = csvText + ",yoGeoNotes",geonotesck = true;
        if (Ext.getCmp("envnotescb").getValue())
            csvText = csvText + ",yoEnvNotes",envnotesck = true;
        if (Ext.getCmp("boxnumbercb").getValue())
            csvText = csvText + ",yoBoxNumber",boxnumberck = true;
        if (Ext.getCmp("isbnumbercb").getValue())
            csvText = csvText + ",yoIsbNumber",isbnumberck = true;
        if (Ext.getCmp("positioncb").getValue())
            csvText = csvText + ",yoPosition",positionck = true;
        if (Ext.getCmp("datefrozencb").getValue())
            csvText = csvText + ",yoDateFrozen",datefrozenck = true;
        if (Ext.getCmp("contributorcb").getValue())
            csvText = csvText + ",yoContributor",contributorck = true;
        if (Ext.getCmp("savedbycb").getValue())
            csvText = csvText + ",yoSavedBy",savedbyck = true;
        if (Ext.getCmp("qcstatuscb").getValue())
            csvText = csvText + ",yoQCStatus";
        if (Ext.getCmp("qcreasoncb").getValue())
            csvText = csvText + ",yoQCReason";
        if (Ext.getCmp("qcnotescb").getValue())
            csvText = csvText + ",yoQCNotes";
        if (Ext.getCmp("qcstatuscb").getValue())
            csvText = csvText + ",yoQCStatus";
        if (Ext.getCmp("mtacb").getValue())
            csvText = csvText + ",yoMTA",mtack = true;
        if (Ext.getCmp("commentscb").getValue())
            csvText = csvText + ",yoComments",commentsck = true;
        csvText = csvText + breakDelimiter;
        csvData.sort(function(a, b) {
            return a[0] - b[0];
        });
        for (var c = 0; c < csvData.length; c++) {
            var cArray = csvData[c];
            for (var ci = 0; ci < cArray.length; ci++) {
                if (cArray[ci] == undefined || cArray[ci] == null) {
                    cArray[ci] = "";
                }
                cArray[ci] = cArray[ci] + "";
                cArray[ci] = cArray[ci].replace(/'/g, "");
                cArray[ci] = cArray[ci].replace(/"/g, "");
                cArray[ci] = '"' + cArray[ci] + '"';
                cArray[ci] = cArray[ci].replace(/YO /, "YO");
            }
            csvText = csvText + "" + cArray[1] + "";
            if (Ext.getCmp("statuscb").getValue())
                csvText = csvText + "," + cArray[3] + "";
            if (aliasck)
                csvText = csvText + "," + cArray[2] + "";
            if (mtck)
                csvText = csvText + "," + cArray[4] + "";
            if (mtmethodck)
                csvText = csvText + "," + cArray[20] + "";
            if (isscck)
                csvText = csvText + "," + cArray[12] + "";
            if (isscmethodck)
                csvText = csvText + "," + cArray[29] + "";
            if (ploidyck)
                csvText = csvText + "," + cArray[21] + "";
            if (ploidymethodck)
                csvText = csvText + "," + cArray[22] + "";
            if (Ext.getCmp("ploidynotescb").getValue())
                csvText = csvText + "," + cArray[30] + "";
            if (genotypeck)
                csvText = csvText + "," + cArray[5] + "";
            if (parentck)
                csvText = csvText + "," + cArray[7] + "";
            if (progenitorck)
                csvText = csvText + "," + cArray[14] + "";
            if (siblingsck)
                csvText = csvText + "," + cArray[27] + "";
            if (continentck)
                csvText = csvText + "," + cArray[15] + "";
            if (countryck)
                csvText = csvText + "," + cArray[16] + "";
            if (localeck)
                csvText = csvText + "," + cArray[17] + "";
            if (geodateck)
                csvText = csvText + "," + cArray[32] + "";
            if (envsourceck)
                csvText = csvText + "," + cArray[18] + "";
            if (geonotesck)
                csvText = csvText + "," + cArray[6] + "";
            if (envnotesck)
                csvText = csvText + "," + cArray[19] + "";
            if (boxnumberck)
                csvText = csvText + "," + cArray[8] + "";
            if (isbnumberck)
                csvText = csvText + "," + cArray[31] + "";
            if (positionck)
                csvText = csvText + "," + cArray[13] + "";
            if (datefrozenck)
                csvText = csvText + "," + cArray[9] + "";
            if (contributorck)
                csvText = csvText + "," + cArray[10] + "";
            if (savedbyck)
                csvText = csvText + "," + cArray[26] + "";
            if (Ext.getCmp("qcstatuscb").getValue())
                csvText = csvText + "," + cArray[23] + "";
            if (Ext.getCmp("qcreasoncb").getValue())
                csvText = csvText + "," + cArray[24] + "";
            if (Ext.getCmp("qcnotescb").getValue())
                csvText = csvText + "," + cArray[25] + "";
            if (Ext.getCmp("mtacb").getValue())
                csvText = csvText + "," + cArray[28] + "";
            if (commentsck)
                csvText = csvText + "," + cArray[11] + "";

            csvText = csvText + breakDelimiter;
        }
        export2Csv("YOSearchedResults.csv", csvText, "yo2Csv");
    }
    
    function setYoAdmin(jsonObj){
    	limsadmin_obj =  jsonObj;
            			yoCount = limsadmin_obj.limsadminYoCount;
                        yoMaxNum = limsadmin_obj.limsadminYoMaxNum;
                        yoBox = limsadmin_obj.limsadminYoBoxNum;
                        yoPosition = limsadmin_obj.limsadminYoPosition;
                        if (yoHash != null && yoHash.clone == undefined){
	                	yoHash = null;
			}
                        Ext.getCmp("showYOSearchResultsId").enable();
                        loadCreateWildStrain(yoHash, function() {
                            Ext.getDom("sample-search-result-list").innerHTML = "";
                            Ext.getDom("yo-form").innerHTML = "";
                            yoForm.render("yo-form");
                        });
     }                   

    // public
    return {

        initYO: function(callback) {
            initYOStore(function() {
                renderYOSearchResult();
                callback();
            });
        },
        getYOPanel: function() {
            loadYOPanel();
            return yoPanel;
        },

        toCSV: function() {
            
		/*var customcboxes = {
                xtype: 'checkboxgroup',
                itemCls: 'x-check-group-alt',
                allowBlank: false,
                anchor: '98%',
                items: [
                    {
                        columnWidth: '.33',
                        items: [
                            {
                                xtype: 'label',
                                text: 'Key Info',
                                cls:'x-form-check-group-label',
                                anchor:'-15'
                            },
                            {
                                boxLabel: 'Alias',
                                checked: true,
                                id: 'aliascb'
                            },
                            {
                                boxLabel: 'MatingType',
                                checked: true,
                                id: 'matingtypecb'
                            },
                            {
                                boxLabel: 'MatingTypeMethod',
                                checked: true,
                                id: 'mtmethodcb'
                            },
                            {
                                boxLabel: 'isSCerevisiae',
                                id: 'issccb'
                            },
                            {
                                boxLabel: 'isSCMethod',
                                checked: false,
                                id: 'isscmethodcb'
                            },
                            {
                                boxLabel: 'Ploidy',
                                id: 'ploidycb'
                            },
                            {
                                boxLabel: 'PloidyMethod',
                                checked: false,
                                id: 'ploidymethodcb'
                            },
                            {
                                boxLabel: 'PloidyNotes',
                                checked: false,
                                id: 'ploidynotescb'
                            },
                            {
                                boxLabel: 'Genotype',
                                id: 'genotypecb',
                                checked: true

                            },
                            {
                                boxLabel: 'Parent',
                                id: 'parentcb',
                                checked: true
                            },
                            {
                                boxLabel: 'Progenitor',
                                id: 'progenitorcb',
                                checked: true
                            },
                            {
                                boxLabel: 'Siblings',
                                id: 'siblingscb',
                                checked: true
                            },
                            {
                                boxLabel: 'Status',
                                id: 'statuscb',
                                checked: true
                            }

                        ]
                    },
                    {
                        columnWidth: '.33',
                        items: [
                            {
                                xtype: 'label',
                                text: 'Geography-Environment-QC',
                                cls:'x-form-check-group-label',
                                anchor:'-15'
                            },
                            {
                                boxLabel: 'Continent',
                                id: 'continentcb'
                            },
                            {
                                boxLabel: 'Country',
                                id: 'countrycb'
                            },
                            {
                                boxLabel: 'Locale',
                                id: 'localecb'
                            },
                            {
                                boxLabel: 'GeoDate',
                                id: 'geodatecb'
                            },
                            {
                                boxLabel: 'EnvSource',
                                id: 'envsourcecb'
                            },
                            {
                                boxLabel: 'GeoNotes',
                                id: 'geonotescb'
                            },
                            {
                                boxLabel: 'EnvNotes',
                                id: 'envnotescb'
                            },
                            {
                                boxLabel: 'QCStatus',
                                id: 'qcstatuscb'
                            },
                            {
                                boxLabel: 'QCReason',
                                id: 'qcreasoncb'
                            },
                            {
                                boxLabel: 'QCNotes',
                                id: 'qcnotescb'
                            }
                        ]
                    },
                    {
                        columnWidth: '.33',
                        items: [
                            {
                                xtype: 'label',
                                text: 'Location-Comments',
                                cls:'x-form-check-group-label',
                                anchor:'-15'
                            },
                            {
                                boxLabel: 'BoxNumber',
                                id: 'boxnumbercb',
                                checked: true
                            },
                            {
                                boxLabel: 'ISBNumber',
                                id: 'isbnumbercb',
                                checked: true
                            },
                            {
                                boxLabel: 'Position',
                                id: 'positioncb',
                                checked: true
                            },
                            {
                                boxLabel: 'Date Frozen',
                                id: 'datefrozencb',
                                checked: true
                            },
                            {
                                boxLabel: 'Contributor',
                                id: 'contributorcb',
                                checked: true
                            },
                            {
                                boxLabel: 'SavedBy',
                                id: 'savedbycb'
                            },
                            {
                                boxLabel: 'MTA',
                                id: 'mtacb'
                            },
                            {
                                boxLabel: 'Comments',
                                id: 'commentscb'
                            }
                        ]
                    }
                ]
            };*/
            var promptWin = new Ext.Window({
                title: 'YO2CSV - Select columns',
                width: 600,
                height: 450,
                autoScroll: true,
                modal: true,
                bodyStyle: 'padding:2px;',
                items: [customcboxes],
                buttons: [
                    {
                        text: 'SelectAll',
                        handler: function() {
                            Ext.getCmp("aliascb").setValue(true);
                            Ext.getCmp("matingtypecb").setValue(true);
                            Ext.getCmp("issccb").setValue(true);
                            Ext.getCmp("isscmethodcb").setValue(true);
                            Ext.getCmp("ploidycb").setValue(true);
                            Ext.getCmp("ploidymethodcb").setValue(true);
                            Ext.getCmp("ploidynotescb").setValue(true);
                            Ext.getCmp("genotypecb").setValue(true);
                            Ext.getCmp("parentcb").setValue(true);
                            Ext.getCmp("progenitorcb").setValue(true);
                            Ext.getCmp("siblingscb").setValue(true);
                            Ext.getCmp("continentcb").setValue(true);
                            Ext.getCmp("countrycb").setValue(true);
                            Ext.getCmp("localecb").setValue(true);
                            Ext.getCmp("geodatecb").setValue(true);
                            Ext.getCmp("envsourcecb").setValue(true);
                            Ext.getCmp("geonotescb").setValue(true);
                            Ext.getCmp("envnotescb").setValue(true);
                            Ext.getCmp("boxnumbercb").setValue(true);
                            Ext.getCmp("isbnumbercb").setValue(true);
                            Ext.getCmp("positioncb").setValue(true);
                            Ext.getCmp("datefrozencb").setValue(true);
                            Ext.getCmp("contributorcb").setValue(true);
                            Ext.getCmp("commentscb").setValue(true);
                            Ext.getCmp("savedbycb").setValue(true);
                            Ext.getCmp("mtacb").setValue(true);
                            Ext.getCmp("statuscb").setValue(true);
                            Ext.getCmp("qcstatuscb").setValue(true);
                            Ext.getCmp("qcreasoncb").setValue(true);
                            Ext.getCmp("qcnotescb").setValue(true);
                        }
                    },
                    {
                        text: 'Reset',
                        handler: function() {
                            Ext.getCmp("aliascb").setValue(true);
                            Ext.getCmp("matingtypecb").setValue(true);
                            Ext.getCmp("issccb").setValue(false);
                            Ext.getCmp("isscmethodcb").setValue(true);
                            Ext.getCmp("ploidycb").setValue(false);
                            Ext.getCmp("ploidymethodcb").setValue(false);
                            Ext.getCmp("ploidynotescb").setValue(false);
                            Ext.getCmp("genotypecb").setValue(true);
                            Ext.getCmp("parentcb").setValue(true);
                            Ext.getCmp("progenitorcb").setValue(true);
                            Ext.getCmp("siblingscb").setValue(false);
                            Ext.getCmp("continentcb").setValue(false);
                            Ext.getCmp("countrycb").setValue(false);
                            Ext.getCmp("localecb").setValue(false);
                            Ext.getCmp("geodatecb").setValue(false);
                            Ext.getCmp("envsourcecb").setValue(false);
                            Ext.getCmp("geonotescb").setValue(false);
                            Ext.getCmp("envnotescb").setValue(false);
                            Ext.getCmp("boxnumbercb").setValue(true);
                            Ext.getCmp("isbnumbercb").setValue(true);
                            Ext.getCmp("positioncb").setValue(true);
                            Ext.getCmp("datefrozencb").setValue(true);
                            Ext.getCmp("contributorcb").setValue(true);
                            Ext.getCmp("commentscb").setValue(false);
                            Ext.getCmp("savedbycb").setValue(false);
                            Ext.getCmp("statuscb").setValue(true);
                            Ext.getCmp("mtacb").setValue(false);
                            Ext.getCmp("qcstatuscb").setValue(false);
                            Ext.getCmp("qcreasoncb").setValue(false);
                            Ext.getCmp("qcnotescb").setValue(false);
                        }
                    },
                    {
                        text: 'Go',
                        handler: function() {                            
                            processYO2CSV(myYOData);                            
                        }
                    }
                ],
                layout: 'fit'
            });
            promptWin.show();
        },

        getYOStore: function() {
            return yoStore;
        },
        loadNewYO: function() {
            Ext.getDom("yad-form").innerHTML = "";
            if (LoggedInUser.userUri == "/addama-users/users/public@systemsbiology.org") {
                Ext.Msg.alert("warning", "Yo do not have permission to create new records");
            } else {
            	getSolrLimsAdmin(setYoAdmin);            	
            }
        },
        loadSearchResult: function() {
            Ext.getDom("sample-search-result-list").innerHTML = "";
            renderYOSearchResult();
        },
        updateMTA: function(key, link){
            updateMTAWithKey("yoKey:" + key, yoFields, "yoMTA", link)
        },
        viewFamilyTree: function() {
            loadFamilyTree();
        },
        viewOmicsTable: function() {
            loadSeqTable();
        },
        loadStrain: function(yoKey) {
            Ext.Ajax.request({
                url: getSolrSearchUrl("yoKey:" + yoKey, 1, yoFields),
                method: "GET",
                success: function(response) {
                    var resp = Ext.util.JSON.decode(response.responseText);
                    yoHash = {};
                    populateSingleStrainViaSearch(yoHash, resp.response.docs[0]);                    
                    yoHash.name = yoKey;
                    loadCreateWildStrain(yoHash, function() {
                        yoFormRender();
                    });
                },
                failure: function() {
                    eventManager.fireStatusMessageEvent({ text: "Error retrieving data for " + yoKey, level: "error" });
                    Ext.Msg.alert("error", "Error retrieving data for " + yoKey);
                }
            });
        },
        setArrayData: function(data) {
                    myYOData = data;
         }
    };
}();
